<?php
function _gen_api_sig($secret, $args) {
    if (empty($secret) || empty($args)) {
        return false;
    }
    $str_args = array();
    ksort($args);
    foreach ($args as $k=>$v) {
        $str_args[] = $k . $v;
    }
    $str_args = join('', $str_args);
    $str = $secret . $str_args;
    #error_log("DEBUG:\t[str4sig]" . $str ."\n", 3, "/tmp/flickr_debug.log");//4debug
    return md5($str);
}

function auth($secret, $key, $perms) {
    if (!in_array($perms, array("write", "read", "delete"))) {
        return false;
    }

    $params = array(
        'api_key'   =>  KEY,
        'perms'  =>  $perms,
    );  

    $api_sig = _gen_api_sig($secret, $params);
    $url = str_replace("{api_key}", $key, URL_AUTH);
    $url = str_replace("{perms}", $perms, $url);
    $url = str_replace("{api_sig}", $api_sig, $url);
    #error_log("DEBUG:\t[url]" . $url ."\n", 3, "/tmp/flickr_debug.log");//4debug
    header("Location: " . $url);
}

function call($method, $param_arr) {
    if (empty($param_arr)) {
        $params = "";
    } else {
        $params = array();
        foreach ($param_arr as $k=>$v) {
            $params[] = $k . "=" . $v;
        }
        $params = "&" . join("&", $params);
    }
    $url = str_replace("{method}", $method, URL_REQ);
    $url = str_replace("{params}", $params, $url);
    error_log("[time]" . date("Y-m-d H:i:s") . " [url]" . $url ."\n", 3, LOGPATH . "/notice.log." . date("Ymd"));
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_NOBODY, false);
    $recv = curl_exec($ch);
    $errno = curl_errno($ch);
    curl_close($ch);
    if ($errno) {
        return false;
    } else {
        preg_match('/jsonFlickrApi\((.*)\)/', $recv, $match);
        return json_decode($match[1]);
    }
}

?>
